#

| Chapter 36 Sorting |

## 36.8 lensort: Sort Lines by Length

A nice little script to sort lines from shortest to longest can be handy when you're writing and want to find your big words:

    deroff uniq
    % deroff -w report | uniq -d | lensort
    a
    an
      ...
    deoxyribonucleic

Once I used it to sort a list of pathnames:

    find
    % find adir -type f -print | lensort
    adir/.x
    adir/.temp
       ...
    adir/subdir/part1/somefile
    adir/subdir/part1/a_test_case

The script uses awk (33.11) to print each line's length, followed by the original line. Next, sort sorts the lengths numerically (36.5). Then sed (34.24) strips off the lengths and the spaces - and prints the lines:

>     #! /bin/sh
>     awk 'BEGIN { FS=RS }
>     { print length, $0 }' $* |
>     # Sort the lines numerically
>     sort +0n -1 |
>     # Remove the length and the space and print each line
>     sed 's/^[0-9][0-9]* //'

(Some awks require a semicolon after the first curly bracket - that is, `{ FS=RS };`.)

- JP

36.7 Sorting Multiline Entries |  | 36.9 Sorting a List of People by Last Name